package gk.example.activity;

import gk.example.App;
import gk.example.BaseActivity;
import gk.example.bean.User;
import gk.example.util.ErrorCodeUtil;
import gk.example.util.T;
import gk.example.view.ProgressDialog;

import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

import com.example.gkdate.R;

/**
 * 
 * Description:登陆界面
 * 
 * @author Wenk.Chan（最新修改者）
 * @version 1.0（最新版本号）
 */

public class LoginActivity extends BaseActivity implements OnClickListener {
	private EditText mEtAccount;
	private EditText mEtPassword;
	private Button mBtnLogin;
	private TextView mTvRegister;
	private TextView mTvForget;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void initView() {
		setContentView(R.layout.activity_login);
		mEtAccount = (EditText) findViewById(R.id.et_login_account);
		mEtPassword = (EditText) findViewById(R.id.et_login_password);
		mBtnLogin = (Button) findViewById(R.id.btn_login);
		mTvForget = (TextView) findViewById(R.id.tv_forget);
		mTvRegister = (TextView) findViewById(R.id.tv_register);
		// 用户登录缓存
//		App.BmobUser = BmobUser.getCurrentUser(this, User.class);
//		if (App.BmobUser != null) {
//			// startActivity(new Intent(LoginActivity.this,
//			// MainActivity.class));
//			// finish();
//		} else {
			App.BmobUser = new User();
//		}
	}

	@Override
	protected void initEvent() {

		mBtnLogin.setOnClickListener(this);
		mTvForget.setOnClickListener(this);
		mTvRegister.setOnClickListener(this);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		mBtnLogin.setVisibility(View.VISIBLE);
	}

	/**
	 * 
	 * 描述：官方登录方法
	 * 
	 * @return void
	 */
	private void login() {
		final String account = mEtAccount.getText().toString();
		String password = mEtPassword.getText().toString();
		if (account.equals("") || password.equals("")) {
			T.show(LoginActivity.this, "请完整填写登录信息", Toast.LENGTH_SHORT);
			return;
		}

		if (!account.equals("") || password.equals("")) {
			mProgressDialog = new ProgressDialog();
			mProgressDialog.setMsg("登录中");
			mProgressDialog.show(getSupportFragmentManager(), "login");
			App.BmobUser.setUsername(account);
			App.BmobUser.setPassword(password);
			App.BmobUser.login(this, new SaveListener() {
				@Override
				public void onSuccess() {
					mProgressDialog.dismiss();
					getAccountData(account);
				}
				@Override
				public void onFailure(int arg0, String arg1) {
					ErrorCodeUtil.Errorshow(LoginActivity.this, arg0, arg1);
					mProgressDialog.dismiss();
				}
			});
		}
	}

	/**
	 * 
	 * 描述：获取用户数据
	 * 
	 * @param account
	 *            当前登录用户
	 * @return void
	 */
	private void getAccountData(String account) {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereEqualTo("username", account);
		query.findObjects(this, new FindListener<User>() {

			@Override
			public void onSuccess(List<User> arg0) {
				App.BmobUser = arg0.get(0);
				finish();
				startActivity(new Intent(LoginActivity.this, MainActivity.class));
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(LoginActivity.this, arg0, arg1);
			}
		});

	}

	/**
	 * 
	 * 描述： 找回密码对话框
	 * 
	 * @return void
	 */
	private void showResetDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setItems(new String[] { "利用手机号码找回密码", "利用邮箱地址找回密码" },
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						switch (which) {
						// 利用手机号找回密码
						case 0:
							checkPhone("reset");
							break;
						// 利用邮箱地址找回密码
						case 1:
							Intent intent = new Intent(LoginActivity.this,
									ResetPasswordActivity.class);
							Bundle bundle = new Bundle();
							bundle.putInt("reset", 0x12);
							intent.putExtras(bundle);
							startActivity(intent);
							finish();
							break;
						default:
							break;
						}
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();

	}

	/**
	 * 
	 * 描述：验证手机号
	 * 
	 * @return void
	 */
	private void checkPhone(final String form) {
		RegisterPage registerPage = new RegisterPage(form);
		registerPage.show(this);
		registerPage.setRegisterCallback(new EventHandler() {
			@Override
			public void afterEvent(int event, int result, Object data) {
				super.afterEvent(event, result, data);
				if (result == SMSSDK.RESULT_COMPLETE) {
					@SuppressWarnings("unchecked")
					HashMap<String, Object> phoneMap = (HashMap<String, Object>) data;
					String phone = (String) phoneMap.get("phone");
					if (form.equals("register")) {
						if (App.BmobUser == null) {
							App.BmobUser = new User();
						}
						App.BmobUser.setContact(phone);
						startActivity(new Intent(LoginActivity.this,
								RegisterActivity.class));
					} else if (form.equals("reset")) {
						Intent intent = new Intent(LoginActivity.this,
								ResetPasswordActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("phone", phone);
						bundle.putInt("reset", 0x11);
						intent.putExtras(bundle);
						startActivity(intent);
						finish();
					}

				}
			}

		});
	}

	/**
	 * 设置点击事件
	 */
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_login:
			login();
			break;
		case R.id.tv_register:
			checkPhone("register");
			mBtnLogin.setVisibility(View.INVISIBLE);
			break;
		case R.id.tv_forget:
			showResetDialog();
			break;
		default:
			break;
		}
	}

}
